/**
 * 
 */
package org.ejc.struts.dashboard;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.ejc.api.convention.ConventionHistoryAPIUtil;
import org.ejc.api.executive.ConventionExecutiveAPIUtil;
import org.ejc.api.registration.RegistrationAPIUtil;
import org.ejc.api.transaction.TransactionAPIUtil;
import org.ejc.datatype.dashboard.DashBoardExecutveDrillDownCriteria;
import org.ejc.persist.model.ConventionActivityHistory;
import org.ejc.persist.model.ConventionExecutive;
import org.ejc.session.EJCSession;

/**
 * @author Brian Boyle
 * @struts.action path="/struts/dashboard/dashboardAction" scope="request"
 *                parameter="methodToCall" name="dashboardForm"
 *                validate="false"
 *                input="/struts/dashboard/dashboard.jsp"
 * 
 * @struts.action-forward name="loadDashSuccess" path="/struts/dashboard/dashboard.jsp"
 * @struts.action-forward name="txDrillDownSuccess" path="/struts/dashboard/drillDownTxs.jsp"
 * @struts.action-forward name="historyListing" path="/struts/dashboard/sessionHistory.jsp"
 * @struts.action-forward name="transactionHistoryListing" path="/struts/dashboard/transactionHistoryListing.jsp"
 * 
 * 
 * 
 */
public class DashboardAction extends DispatchAction {

	private static final int resultSetIndex = 0;
	private static final int resultSetSize = 100;
	
	
	private double getPreRegValue(){
		try {
			return TransactionAPIUtil.getLocalHome().create().getTotalPreRegisteredTxValue();
		} catch (CreateException e) {
			log.fatal(e);
		} catch (NamingException e) {
			log.fatal(e);
		}
		return 0;
	}
	
	private double getCurrentRegValue(){
		try {
			return TransactionAPIUtil.getLocalHome().create().getTotalRegisteredTxValue();
		} catch (CreateException e) {
			log.fatal(e);
		} catch (NamingException e) {
			log.fatal(e);
		}
		return 0;
	}
	
	
	
	/**
	 * 
	 */
	public DashboardAction() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public final ActionForward loadDash(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		Integer onSiteGuests = getNumOfOnsiteGuests();
		Integer pendingArrivalGuests = getNumOfPendingArrivalGuests();
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard");
		
		boolean isConvActive=RegistrationAPIUtil.getLocalHome().create().isConventionActive();
		if(isConvActive){
			ejcSession.getConvention().setConventionStatus("ACTIVE");
		}else{
			ejcSession.getConvention().setConventionStatus("INACTIVE");
			Date fromDate=RegistrationAPIUtil.getLocalHome().create().getLastActiveDate();
			Date toDate=RegistrationAPIUtil.getLocalHome().create().getLastInActiveDate();
			List txListing=TransactionAPIUtil.getLocalHome().create().getExecTransactions(fromDate,toDate);
			request.setAttribute("txListing",txListing);
			request.setAttribute("fromDate",fromDate);
			request.setAttribute("toDate",toDate);
		}
		
		
		request.setAttribute("onSiteGuests", onSiteGuests);
		request.setAttribute("pendingArrivalGuests", pendingArrivalGuests);
		request.setAttribute("totalGuests", pendingArrivalGuests + onSiteGuests);
		
		double preReg=getPreRegValue();
		double curReg=getCurrentRegValue();
		request.setAttribute("totalPreRegVal",preReg);
		request.setAttribute("totalRegVal",curReg);
		request.setAttribute("totalValue",preReg+curReg);
		
		
		return mapping.findForward("loadDashSuccess");
	}
	
	private Integer getNumOfOnsiteGuests(){
		Integer numOfGuests = 0;
		try {
			numOfGuests = RegistrationAPIUtil.getLocalHome().create().selectNumOfGuests(new Integer(1));
		} catch (CreateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return numOfGuests;
	}
	
	private Integer getNumOfPendingArrivalGuests(){
		Integer numOfGuests = 0;
		try {
			numOfGuests = RegistrationAPIUtil.getLocalHome().create().selectNumOfGuests(new Integer(2));
		} catch (CreateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return numOfGuests;
	}
	
	
	
	public final ActionForward pauseRegistration(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		//todo: check to see if we are paused already !
		Integer onSiteGuests = getNumOfOnsiteGuests();
		Integer pendingArrivalGuests = getNumOfPendingArrivalGuests();
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard");
		request.setAttribute("onSiteGuests", onSiteGuests);
		request.setAttribute("pendingArrivalGuests", pendingArrivalGuests);
		request.setAttribute("totalGuests", pendingArrivalGuests + onSiteGuests);
		
		
		
		ejcSession.getConvention().setConventionStatus("INACTIVE");
		
		
		//get last active date
		Date d=RegistrationAPIUtil.getLocalHome().create().getLastActiveDate();
		//pause reg
		RegistrationAPIUtil.getLocalHome().create().pauseRegistration();
		
		Date now=new Date();
		List txListing=TransactionAPIUtil.getLocalHome().create().getExecTransactions(d,now);
		request.setAttribute("txListing",txListing);
		request.setAttribute("fromDate",d);
		request.setAttribute("toDate",now);
		
		
		
		
		
		return mapping.findForward("loadDashSuccess");
	}
	

	public final ActionForward activateRegistration(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		Integer onSiteGuests = getNumOfOnsiteGuests();
		Integer pendingArrivalGuests = getNumOfPendingArrivalGuests();
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard");
		request.setAttribute("onSiteGuests", onSiteGuests);
		request.setAttribute("pendingArrivalGuests", pendingArrivalGuests);
		request.setAttribute("totalGuests", pendingArrivalGuests + onSiteGuests);
		RegistrationAPIUtil.getLocalHome().create().activateRegistration();
		ejcSession.getConvention().setConventionStatus("ACTIVE");
		return mapping.findForward("loadDashSuccess");
	}
	
	public  final ActionForward doPreReg(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		RegistrationAPIUtil.getLocalHome().create().test();
		//TransactionAPIUtil.getLocalHome().create().getTotalRegisteredTxValue();
		return mapping.findForward("loadDashSuccess");
	}

	/*
	 ***************************************************************************************
	 ******************************** executiveDrillDown ***********************************
	 ***************************************************************************************
	 */
	
	public final ActionForward drillDownIntoTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		
		DashboardForm dashForm=(DashboardForm)form;
		Integer execId=dashForm.getExecutiveId();
		log.fatal("Lookin for "+execId);
		List listing=TransactionAPIUtil.getLocalHome().create().getCurrentSessionTransactionsForExecutive(execId, resultSetIndex, resultSetSize);
		request.setAttribute("txListing",listing);

		Date fromDate=RegistrationAPIUtil.getLocalHome().create().getLastActiveDate();
		Date toDate=RegistrationAPIUtil.getLocalHome().create().getLastInActiveDate();
		ConventionExecutive executive=ConventionExecutiveAPIUtil.getLocalHome().create().getExecutive(execId);
		
		request.setAttribute("executive",executive);
		request.setAttribute("toDate",toDate);
		request.setAttribute("fromDate",fromDate);
		
		//Set the current Search Criteria in the session object
		DashBoardExecutveDrillDownCriteria criteria = new DashBoardExecutveDrillDownCriteria();
		criteria.setExecutive(executive);
		criteria.setFromDate(fromDate);
		criteria.setToDate(toDate);
		ejcSession.setCriteria(criteria);
		ejcSession.setResultIndex(resultSetIndex);
		ejcSession.setResultSize(resultSetSize);
		request.setAttribute("initialSearch", true);
		if(listing.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
		return mapping.findForward("txDrillDownSuccess");
	}
	
	public void drillDownIntoTransactionsPaging(HttpServletRequest request, int resultSize, int resultIndex) throws Exception 
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		DashBoardExecutveDrillDownCriteria criteria = (DashBoardExecutveDrillDownCriteria) ejcSession.getCriteria();
		//Get the list of transactions
		List listing=TransactionAPIUtil.getLocalHome().create().getCurrentSessionTransactionsForExecutive(criteria.getExecutive().getExecutiveId(), resultIndex, resultSize);
		request.setAttribute("txListing",listing);

		request.setAttribute("executive",criteria.getExecutive());
		request.setAttribute("toDate", criteria.getToDate());
		request.setAttribute("fromDate",criteria.getFromDate());
		
		ejcSession.setResultIndex(resultIndex);
		ejcSession.setResultSize(resultSetSize);
		
		if(listing.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
		
	}
	
	/**
	 * Search the next results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchNext(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() + resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		drillDownIntoTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("txDrillDownSuccess");
	}
	
	/**
	 * Search the previous results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchPrevious(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() - resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		drillDownIntoTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("txDrillDownSuccess");
	}
	
	
	
	public final ActionForward viewPreviousSessions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		DashboardForm dashForm=(DashboardForm)form;
		List listing=ConventionHistoryAPIUtil.getLocalHome().create().getConventionHistories(new Integer(1));
		request.setAttribute("historyListing", listing);
		
		
		EJCSession ejcSession = (EJCSession) request.getSession().getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard <img src=\"../../img/triangle.gif\"> View Previous Sessions Txs");
		return mapping.findForward("historyListing");
	}
		
	/*
	 ***************************************************************************************
	 ******************************** viewSessionHistoryTransactions ***********************
	 ***************************************************************************************
	 */
	
	public final ActionForward viewSessionTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		DashboardForm dashForm=(DashboardForm)form;
		Integer txHistoryId=dashForm.getTxHistoryId();
		List txListing=TransactionAPIUtil.getLocalHome().create().getTransactionListingForActivityPeriod(txHistoryId, resultSetIndex, resultSetSize);
		request.setAttribute("txListing",txListing);
		
		ConventionActivityHistory history=ConventionHistoryAPIUtil.getLocalHome().create().getConventionHistory(txHistoryId);
		SimpleDateFormat f=new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss");
		
		String fromDate=f.format(new Date(history.getStartTime().getTime()));
		String toDate=f.format(new Date(history.getEndTime().getTime()));
		
		EJCSession ejcSession = (EJCSession) request.getSession().getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard <img src=\"../../img/triangle.gif\"> View Previous Sessions Txs"+
				" <img src=\"../../img/triangle.gif\"> From :"+fromDate+" To :"+toDate);
		ejcSession.setTrxHistoryId(txHistoryId);
		request.setAttribute("sessionHistoryView", true);
		request.setAttribute("initialSearch", true);
		ejcSession.setResultIndex(resultSetIndex);
		ejcSession.setResultSize(resultSetSize);
		if(txListing.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
		
		return mapping.findForward("transactionHistoryListing");
	}
	
	public void viewSessionTransactionsPaging(HttpServletRequest request, int resultSize, int resultIndex) throws Exception 
	{
		EJCSession ejcSession = (EJCSession) request.getSession().getAttribute("ejcSession");
		
		Integer txHistoryId=ejcSession.getTrxHistoryId();
		List txListing=TransactionAPIUtil.getLocalHome().create().getTransactionListingForActivityPeriod(txHistoryId, resultIndex, resultSize);
		request.setAttribute("txListing",txListing);
		
		ConventionActivityHistory history=ConventionHistoryAPIUtil.getLocalHome().create().getConventionHistory(txHistoryId);
		SimpleDateFormat f=new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss");
		
		String fromDate=f.format(new Date(history.getStartTime().getTime()));
		String toDate=f.format(new Date(history.getEndTime().getTime()));
		
		
		ejcSession.setCurrentAction("Dashboard <img src=\"../../img/triangle.gif\"> View Previous Sessions Txs"+
				" <img src=\"../../img/triangle.gif\"> From :"+fromDate+" To :"+toDate);
				
		request.setAttribute("sessionHistoryView", true);
		ejcSession.setResultIndex(resultIndex);
		ejcSession.setResultSize(resultSetSize);
		if(txListing.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
		
	}
	
	/**
	 * Search the next results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchNextSessionTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() + resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		viewSessionTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("transactionHistoryListing");
	}
	
	/**
	 * Search the previous results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchPreviousSessionTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() - resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		viewSessionTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("transactionHistoryListing");
	}
	
	/*
	 ***************************************************************************************
	 ******************************** viewCurrentTransactions ******************************
	 ***************************************************************************************
	 */
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward viewCurrentTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		EJCSession ejcSession = (EJCSession) request.getSession().getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard <img src=\"../../img/triangle.gif\"> View Current Txs");
		List txList=TransactionAPIUtil.getLocalHome().create().getAllCurrentSessionTransactions(ejcSession.getConvention().getConventionId(), resultSetIndex, resultSetSize);
		request.setAttribute("txListing",txList);

		ejcSession.setResultIndex(resultSetIndex);
		ejcSession.setResultSize(resultSetSize);
		request.setAttribute("initialSearch", true);
		if(txList.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
		return mapping.findForward("transactionHistoryListing");
	}
	
	public void viewCurrentTransactionsPaging(HttpServletRequest request, int resultSize, int resultIndex) throws Exception 
	{
		EJCSession ejcSession = (EJCSession) request.getSession().getAttribute("ejcSession");
		ejcSession.setCurrentAction("Dashboard <img src=\"../../img/triangle.gif\"> View Current Txs");
		List txList=TransactionAPIUtil.getLocalHome().create().getAllCurrentSessionTransactions(ejcSession.getConvention().getConventionId(), resultIndex, resultSize);
		request.setAttribute("txListing",txList);
		
		ejcSession.setResultIndex(resultIndex);
		ejcSession.setResultSize(resultSetSize);
		
		if(txList.size() < resultSetSize){
			request.setAttribute("noNext", true);
		}
		if(ejcSession.getResultIndex() == 0){
			request.setAttribute("noPrevious", true);
		}
	}
	
	/**
	 * Search the next results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchNextCurrentTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() + resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		viewCurrentTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("transactionHistoryListing");
	}
	
	/**
	 * Search the previous results in the resultSet
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public final ActionForward searchPreviousCurrentTransactions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		int minResult = ejcSession.getResultIndex() - resultSetSize;
		int	maxResult = ejcSession.getResultSize();
		viewCurrentTransactionsPaging(request, maxResult, minResult);
		return mapping.findForward("transactionHistoryListing");
	}
	
	
}
